import { fileURLToPath, URL } from 'node:url'
import path from 'path'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from '@vant/auto-import-resolver'
import AutoImport from 'unplugin-auto-import/vite'
import autoprefixer from 'autoprefixer'
import px2viewport from 'postcss-px-to-viewport-8-plugin'
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'
import Unocss from 'unocss/vite'
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
import { viteVConsole } from 'vite-plugin-vconsole'
import Compression from 'vite-plugin-compression'
import legacy from '@vitejs/plugin-legacy'
import { viteSingleFile } from 'vite-plugin-singlefile'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  return {
    base: mode === 'offline' ? './' : '/',
    plugins: [
      vue(),
      vueJsx(),
      Components({
        dirs: ['src/components'],
        extensions: ['vue'],
        dts: true,
        directoryAsNamespace: true,
        resolvers: [VantResolver()]
      }),
      AutoImport({
        dts: true,
        imports: ['vue', 'vue-router', 'pinia', 'vue-i18n'],
        dirs: ['src/stores/**'],
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/],
        resolvers: [VantResolver()]
      }),
      Compression({
        filter: /\.(js|css|html|svg|png|jpg|gif)$/i,
        threshold: 1024 * 100,
        algorithm: 'gzip'
      }),
      VueI18nPlugin({
        // defaultSFCLang: 'json',
        compositionOnly: false
      }),
      Unocss(),
      viteVConsole({
        entry: path.resolve('src/main.ts'),
        enabled: mode === 'production'
      }),
      mode === 'mock' &&
        mockDevServerPlugin({
          prefix: env.VITE_HTTP_BASE_URL,
          log: true,
          reload: true,
          include: ['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}'],
          formidableOptions: {
            uploadDir: path.join(process.cwd(), 'mock/uploads')
          }
        }),
      mode === 'offline' && [legacy({ targets: ['defaults', 'not IE 11'] }), viteSingleFile()]
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        assets: path.resolve(__dirname, 'assets')
      }
    },
    css: {
      postcss: {
        plugins: [autoprefixer(), px2viewport({ viewportWidth: 375 })]
      },
      preprocessorOptions: {
        less: {
          javascriptEnabled: true
        }
      }
    },
    server: {
      port: 3000,
      open: true,
      proxy: {
        [env.VITE_HTTP_BASE_URL]: {
          target: env.VITE_APP_PROXY,
          changeOrigin: true
        }
      }
    }
  }
})
